//
//  NSString+category_CCKit.m
//  CCKit
//
//  Created by tucici on 2019/3/18.
//  Copyright © 2019 tucici. All rights reserved.
//

#import "NSString+category_CCKit.h"
#import <objc/runtime.h>
//
@interface NSObject ()


@end

static  NSDictionary *dictKey = nil;
@implementation NSString (category_CCKit)
- (void)setDict:(NSDictionary *)dict
{
    objc_setAssociatedObject(self, &dictKey, dict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSDictionary *)dict
{
    return [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    //        return objc_getAssociatedObject(self, &dictKey);
}
/**
 *@pragma 给定固定的宽度，动态获取字符串高度
 */
- (CGRect )getHeightWithWidth:(CGFloat)width withFont:(UIFont *)font
{
    CGSize size = CGSizeMake(width, MAXFLOAT);
    return [self boundingRectWithSize:size
                              options:NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin
                           attributes:@{NSFontAttributeName:font}
                              context:nil];
}
/**
 *@pragma html换段落格式
 */
- (NSString *)formatFromHTML
{
    NSString *text = self;
    text = [text stringByReplacingOccurrencesOfString:@"<p>" withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"</p>" withString:@"\n"];
    text = [text stringByReplacingOccurrencesOfString:@"<u>" withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"</u>" withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"<strong>" withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"</strong>" withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"<em>" withString:@""];
    text = [text stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
    return text;
}

/**
 *@pragma 设置html中图片大小（会自动等比例缩放）
 */
- (NSString *)autoHTMLIMGSizeWithWidth:(CGFloat)width
{
    return [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>%@",width,self];
}

/**
 *@pragma 获取html里的图片的地址
 */
- (NSArray *)urlFromHTML
{
    if (self.length == 0)
    {
        return nil;
    }
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    //标签匹配
    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:@"http://(.*?)\"" options:0 error:NULL];
    //获取符合标签的数组
    NSArray* match = [reg matchesInString:self options:0 range:NSMakeRange(0, [self length] - 1)];
    for (NSTextCheckingResult * result in match)
    {
        //过去数组中的标签
        NSRange range = [result range];
        NSString * imageURL = [self substringWithRange:NSMakeRange(range.location, range.length - 1)];
        //将提取出的图片URL添加到图片数组中
        [array addObject:imageURL];
    }
    return array;
}

/**
 *@pragma获取html中图片的总高度
 */
- (CGFloat)totalHTMLIMGHeightWithWidth:(CGFloat)width
{
    CGFloat totalH  = 0;
    NSArray *array = [self urlFromHTML];
    for (NSString *string in array)
    {
        NSURL *url = [[NSURL alloc] initWithString:string];
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];
        
        UIImage *image = [[UIImage alloc] initWithData:data];
        //倍数
        CGFloat scale = width * 1.0 / image.size.width;
        totalH = totalH + image.size.height * scale;
    }
    return totalH;
}

/**
 *@pragma 获取汉字的拼音
 */
- (NSString *)pinyin
{
    NSMutableString *source = [self mutableCopy];
    CFStringTransform((CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);//这一行是去声调的
    return source;
}
- (NSString *)urlEncode
{
    if (!self) return nil;
    NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\|";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    return [self stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
}
- (NSString *)urlDecode
{
    return [self stringByRemovingPercentEncoding];
}
- (NSMutableAttributedString *)UnderlineWithColor:(UIColor *)color inRange:(NSRange)range
{
    NSMutableAttributedString *attStr  = [[NSMutableAttributedString alloc] initWithString:self];
    [attStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
    [attStr addAttribute:NSUnderlineColorAttributeName value:color range:range];
    [attStr addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(range.location - 1, range.length + 2)];
    return attStr;
}
- (CGSize)sizeWithFont:(UIFont *)font
{
    CGSize size = [self sizeWithAttributes:@{NSFontAttributeName:((font)?font:[UIFont systemFontOfSize:[UIFont systemFontSize]])}];
    return CGSizeMake(ceil(size.width), ceil(size.height));
}
- (CGSize)sizeWithFont:(UIFont *)font inWidth:(CGFloat )width
{
    CGSize size = CGSizeMake(width, MAXFLOAT);
    CGRect rect = [self boundingRectWithSize:size
                                     options:NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName:font}
                                     context:nil];
    return CGSizeMake(ceil(rect.size.width), ceil(rect.size.height));
}
/**
 *@pragma 判断是否整型
 */
- (BOOL)isInt
{
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}
/**
 *@pragma 判断是否浮点型
 */
- (BOOL)isFloat
{
    NSScanner* scan = [NSScanner scannerWithString:self];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}
/**
 *@pragma 判断是否手机号码
 */
- (BOOL)isMobile
{
    NSString *MOBILE = @"^1(3[0-9]|4[579]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
    NSPredicate *mobilePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [mobilePredicate evaluateWithObject:self];
}
/**
 *@pragma 判断是否中文
 */
- (BOOL)isChinese
{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}
/**
 *@pragma 判断是否数字和字母混合
 */
- (BOOL)isNumberOrAlphabet
{
    NSString *match = @"^([a-zA-Z0-9]|[a-z]|[A-Z]|[0-9])+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}
/**
 *@pragma 判断是不是空格
 */
- (BOOL)isSpace
{
    NSString *match = @"^[\\s]+$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}

/**
 *@pragma 判断是否纯数字
 */
- (BOOL)isNumber
{
    NSString *match = @"[0-9]*";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}
/**
 *@pragma 判断是否小写字母开头，并且长度在x-y位(用于账号注册的时候)
 */
- (BOOL)isLowercaseBetween:(int)X and:(int)Y;
{
    NSString *match = [NSString stringWithFormat:@"^([a-z]|[a-zA-Z0-9]){%d,%d}$",X ,Y];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}
/**
 *@pragma 判断是否身份证
 */
- (BOOL)isIDCart
{
    if (self.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if([identityStringPredicate evaluateWithObject:self])
    {
        //** 开始进行校验 *//
        //将前17位加权因子保存在数组里
        NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
        //这是除以11后，可能产生的11位余数、验证码，也保存成数组
        NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
        //用来保存前17位各自乖以加权因子后的总和
        NSInteger idCardWiSum = 0;
        for(int i = 0;i < 17;i++) {
            NSInteger subStrIndex  = [[self substringWithRange:NSMakeRange(i, 1)] integerValue];
            NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
            idCardWiSum      += subStrIndex * idCardWiIndex;
        }
        //计算出校验码所在数组的位置
        NSInteger idCardMod=idCardWiSum%11;
        //得到最后一位身份证号码
        NSString *idCardLast= [self substringWithRange:NSMakeRange(17, 1)];
        
        //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
        if(idCardMod==2)
        {
            if(![idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"])
            {
                return NO;
            }
        }
        else
        {
            //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
            if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]])
            {
                return NO;
            }
        }
        return YES;
    }
    return NO;
}
/// 按照符号，把NSString截取换成NSMutableArray
/// @param symbol 特定符号: -/.=等等
- (NSMutableArray *)arrayWithSymbol:(NSString *)symbol
{
    NSString *string = @"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\"";
    NSString *alertString = [NSString stringWithFormat:@"=======特殊字符集合不包含   %@   ",symbol];
    NSAssert([string containsString:symbol], alertString);
    NSCharacterSet*set = [NSCharacterSet characterSetWithCharactersInString:string];
    return [NSMutableArray arrayWithArray:[self componentsSeparatedByString:symbol]];
}
/// 当字符串为nil  / Null /  [NSNull Class] / length==0  的时候，返回空字符串@""
+ (NSString *)filterNil:(id)string
{
    if (string == nil || string == NULL)
        return @"";
    else if ([string isKindOfClass:[NSNull class]])
        return @"";
    else  if ([string length] == 0)
        return @"";
    else
        return string;
}
@end
